package org.ru.mse10.cvis.web.bean.action.administration;

import java.util.List;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.persistence.Query;

import org.ru.mse10.cvis.entity.system.SystemDefaults;
import org.ru.mse10.cvis.service.EntityService;
import org.ru.mse10.cvis.util.CommonUtil;
import org.ru.mse10.cvis.web.bean.action.BaseAction;

/**
 * The Class SysDefaultsAction.
 */
@SessionScoped
@ManagedBean(name = "sysDefaultsAction")
public class SysDefaultsAction extends BaseAction<SystemDefaults> {

	/** The service. */
	@EJB
	private EntityService service;

	/**
	 * Inits the.
	 * 
	 * @return the string
	 */
	public String init() {
		SystemDefaults systemDefaults = retrieveSystemDefault();
		setTargetEntity(systemDefaults);
		setReadonly(true);
		return "systemDefaultDetails";
	}

	/**
	 * Retrieve system default.
	 * 
	 * @return the system defaults
	 */
	private SystemDefaults retrieveSystemDefault() {
		SystemDefaults defaults = null;
		Query query = service.createQuery("from SystemDefaults");

		@SuppressWarnings("unchecked")
		List<SystemDefaults> resultList = query.getResultList();
		if (CommonUtil.isEmpty(resultList)) {
			defaults = new SystemDefaults();
		} else {
			if (resultList.size() != 1) {
				throw new RuntimeException(
						"There should be only one system defaults record");
			}
			defaults = resultList.get(0);
		}
		return defaults;
	}
}
